<template>
  <div class="container">
    <el-form label-width="90px" :model="query">
      <div class="search">
        <el-form-item label="创建人姓名">
          <el-input clearable v-on:change="getData()" v-model="query.userName" placeholder="请输入创建人"></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input clearable v-model="query.title" v-on:change="getData()" placeholder="请输入新闻标题"></el-input>
        </el-form-item>
        <el-form-item label="请选择栏目">
          <el-select clearable v-model="query.categoryId" v-on:change="getData()" placeholder="请选择栏目">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="新闻状态">
          <el-select clearable v-model="query.newsStatus" v-on:change="getData()" placeholder="请选择新闻状态">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div style="margin-left: 1rem">
          <el-button type="primary" v-on:click="query.offset = 1; getData()">搜索</el-button>
          <el-button type="primary" v-on:click="resert()">重置</el-button>
          <el-button type="primary" :disabled="multipleSelection.length == 0" plain @click="sortClict()">发布</el-button>
          <!-- <el-button type="primary" :disabled="multipleSelection.length == 0" @click="newsPublish">提交审核</el-button> -->
          <!-- <el-button type="primary" @click="newsApprove">审批</el-button> -->
          <el-button type="primary" @click="newsTop">置顶</el-button>
          <el-button type="primary" @click="newsUntop">取消置顶</el-button>
          <el-button type="danger" @click="newsDelete">删除</el-button>
          <el-button type="danger" @click="newsDisable">停用</el-button>
          <el-button type="danger" @click="newsEnable">启用</el-button>
        </div>
      </div>
    </el-form>
    <div class="tables">
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" border style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" width="55">
        </el-table-column>
        <el-table-column prop="title" align="center" label="标题" width="120">
        </el-table-column>
        <el-table-column prop="categoryName" align="center" label="栏目" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" label="新闻状态" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.newsStatus == '0'">待提交</span>
            <span v-if="scope.row.newsStatus == '1'">待审核</span>
            <span v-if="scope.row.newsStatus == '2'">已审核</span>
            <span v-if="scope.row.newsStatus == '3'">驳回（审批不通过)</span>
            <span v-if="scope.row.newsStatus == '4'">停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" align="center" label="置顶" width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.isTop == '0'">未置顶</span>
            <span v-if="scope.row.isTop == '1'">已置顶</span>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" align="center" label="创建人" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="日期" align="center">
          <template slot-scope="scope">{{ scope.row.modifyTime }}</template>
        </el-table-column>
        <el-table-column prop="pageView" align="center" label="浏览次数" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="supportNum" align="center" label="点赞次数" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="address" align="center" label="发送状态" width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.sendNum == '0'">未发布</span>
            <span v-if="scope.row.sendNum >= '1'">已发布</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="text"
              :disabled="scope.row.newsStatus == '1'"
              @click="gotoPublish('edit', scope.row.id)"
              >编辑</el-button
            > -->
            <el-button type="text" @click="publish(scope.row)">发布</el-button>
            <el-button size="mini" type="text" @click="viewDetails(scope.row.id)">查看</el-button>
            <!-- <el-button size="mini" type="text" @click="newsRejected(scope.row)">驳回</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination :query="query" @getData="getData" :total="total" />
      </div>
    </div>
    <el-dialog title="发布排序" :visible.sync="sortShow">
      <div class="caseAdd">
        <div style="padding-bottom:10px">
          <span style="margin-right:10px;margin-top:10px">是否定时发送</span>
          <el-switch v-model="send.isTime" style="padding-bottom:3px" active-color="#13ce66" @change="change($event)">
          </el-switch>
        </div>
        <div class="block" v-if="send.isTime" style="padding-bottom:10px">
              <span class="demonstration" style="margin-right:10px">请选择时间</span>
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss"
               format="yyyy-MM-dd HH:mm:ss" v-model="send.sendDate" type="datetime" placeholder="选择日期时间" :picker-options="pickerOptions">
              </el-date-picker>
            </div>
        <el-table row-key="id" id="projectList" ref="dragTable" :data="sortList" style="width: 100%" border>
          <el-table-column prop="title" align="center" label="标题" width="120">
          </el-table-column>
          <el-table-column prop="creatorName" align="center" label="创建人" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="categoryName" align="center" label="栏目" show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog">
          <el-button @click="sortShow = false">取 消</el-button>
          <el-button type="primary" @click="sortConfirm()">确 定</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="选择组织" :visible.sync="dialogOrgData">
      <el-checkbox-group v-model="deptIdList">
        <el-checkbox v-for="item in orgData" :label="item.id" :key="item.id">{{
          item.corpName
        }}</el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSendOrg()">取 消</el-button>
        <el-button type="primary" @click="sureOrgData()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import { findCategoryData,newsTop,newsUntop, newsDelete,newsDisable,newsEnable} from "../../api/index";
import Pagination from "@/components/Pagination";
import {
  newsFindPage,
  newsSubmit,
  sendMsg,
  findOrgData,
} from "../../api/index";
export default {
  name: "invitation",
  components: { Pagination },
  data () {
    
    return {
      dialogOrgData: false,
      sortShow: false,
      total: 0,
      query: {
        offset: 1,
        limit: 10,
        title: "",
        userName: "",
        startDate: "",
        endDate: "",
        title: "",
        categoryId: "",
        newsStatus: '',
      },
      sortList: [],
      tableData: [],
      multipleSelection: [],
      options: [],
     // 设置不能选则当天之前的时间    写data()中
pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
},
      options1: [
        { value: '0', label: '待提交' },
        { value: '1', label: '待审核' },
        { value: '2', label: '已审核' },
        { value: '3', label: '驳回（审批不通过)' },
        { value: '4', label: '停用' },
      ],
      orgData: [],
      deptIdList: [],
      send: {
        ids: "",
        useridList: "",
        deptIdList: "",
        orgIds: '',
        isTime: false,
        sendDate:'',
        toAllUser:'',
      },
    };
  },
  //   mounted () {
  //   // 调用 table拖拽排序
  //   this.rowDrop()
  // },
  created () {
    this.getData();
    this.getCategoryData();
  },
  methods: {
    async newsDisable() {
      //停用
      let data = await this.$publicJS.delConfirm("是否停用");
      if (data) {
        const ids = this.multipleSelection.map((item) => item.id).join(",");
        let res = await newsDisable({ ids: ids });
        if (res.data.status == 100) {
          this.$message.success("停用成功");
          this.getData();
        }
      }
    },
    async newsDelete() {
      //删除
      let data = await this.$publicJS.delConfirm("是否删除这条新闻");
      if (data) {
        const ids = this.multipleSelection.map((item) => item.id).join(",");
        let res = await newsDelete({ ids: ids });
        if (res.data.status == 100) {
          this.$message.success("删除成功");
          this.getData();
        }
      }
    },
    async newsUntop() {
      //取消置顶
      const ids = this.multipleSelection.map((item) => item.id).join(",");
      let res = await newsUntop({ ids: ids });
      if (res.data.status == 100) {
        this.$message.success("取消置顶成功");
        this.getData();
      }
    },
    async newsEnable() {
      //启用
      let data = await this.$publicJS.delConfirm("是否启用");
      if (data) {
        const ids = this.multipleSelection.map((item) => item.id).join(",");
        let res = await newsEnable({ ids: ids });
        if (res.data.status == 100) {
          this.$message.success("启用成功");
          this.getData();
        }
      }
    },
    async newsTop() {
      //置顶
      const ids = this.multipleSelection.map((item) => item.id).join(",");
      let res = await newsTop({ ids: ids });
      if (res.data.status == 100) {
        this.$message.success("置顶成功");
        this.getData();
      }
    },
    change (data) {
      console.log('%c [ data ]-190', 'font-size:13px; background:pink; color:#bf2c9f;', data)
    },
    // 行拖拽
    rowDrop () {
      let tbody = document.querySelector(".caseAdd .el-table__body-wrapper tbody");
      console.log('%c [ tbody ]-163', 'font-size:13px; background:pink; color:#bf2c9f;', tbody)
      let _this = this
      Sortable.create(tbody, {
        // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
        group: {
          name: 'words',
          pull: true,
          put: true
        },
        animation: 150, // ms, number 单位：ms，定义排序动画的时间
        onAdd: function (evt) { // 拖拽时候添加有新的节点的时候发生该事件
          console.log('onAdd.foo:', [evt.item, evt.from])
        },
        onUpdate: function (evt) { // 拖拽更新节点位置发生该事件
          console.log('onUpdate.foo:', [evt.item, evt.from])
        },
        onRemove: function (evt) { // 删除拖拽节点的时候促发该事件
          console.log('onRemove.foo:', [evt.item, evt.from])
        },
        onStart: function (evt) { // 开始拖拽出发该函数
          console.log('onStart.foo:', [evt.item, evt.from])
        },
        onSort: function (evt) { // 发生排序发生该事件
          console.log('onUpdate.foo:', [evt.item, evt.from])
        },
        onEnd ({ newIndex, oldIndex }) { // 结束拖拽
          let currRow = _this.sortList.splice(oldIndex, 1)[0]
          _this.sortList.splice(newIndex, 0, currRow)
          console.log('%c [ _this.sortList ]-193', 'font-size:13px; background:pink; color:#bf2c9f;', _this.sortList)
        }
      })
    },

    cancelSendOrg () {
      this.dialogOrgData = false;
      this.deptIdList = [];
      this.canceSendOrg = [];
    },
    async sureOrgData () {
      // if (this.deptIdList.length == 0)
      // {
      //   this.$message.error("至少选择一个组织");
      //   return
      // }
      const ids = this.sortList.map((item) => item.id).join(",");
      console.log('%c [ ids ]-226', 'font-size:13px; background:pink; color:#bf2c9f;', ids)
      this.send.orgIds = this.deptIdList.join(",");
      this.send.ids = ids;
      this.send.toAllUser = true
      let res = await sendMsg(this.send);
      if (res.data.status == 100)
      {
        this.send = {
          deptIdList: "",
          ids: "",
          orgIds: '',
          useridList: "",
        };
        this.dialogOrgData = false;
        this.$message.success('发布成功')
        this.getData();
      }
    },
    resert () {
      this.query = {
        offset: 1,
        limit: this.query.limit,
        startDate: "",
        endDate: "",
        newsStatus: '',
        userName: "",
        title: "",
        categoryId: "",
      };
      this.getData();
    },
    async getCategoryData () {
      let res = await findCategoryData();
      if (res.data.status == 100)
      {
        this.options = res.data.data.map((res) => {
          return {
            value: res.id,
            label: res.name,
          };
        });
      }
    },

    async newsPublish () {
      const ids = this.multipleSelection.map((item) => item.id).join(",");
      let res = await newsSubmit({ ids: ids });
      if (res.data.status == 100)
      {
        this.$message("提交审核成功");
        this.getData();
      }
    },
    async getData () {
      //获取数据
      let res = await newsFindPage(this.query);
      if (res.data.status == 100)
      {
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
      }
    },
    viewDetails (id) {
      this.$router.push({
        path: "/newsDetails",
        query: {
          id: id,
        },
      });
    },
    async sendMsg () {
      let result = await this.$ddapi.selectOrg();
      if (result.users.length || result.departments.length)
      {
        if (result.users.length)
        {
          this.send.useridList = result.users
            .map((item) => item.emplId)
            .join(",");
        }
        if (result.departments.length)
        {
          this.send.orgIds = result.departments
            .map((item) => item.id)
            .join(",");
        }
        console.log(this.send, "ssss")
        this.send.ids = this.sortList.map((item) => item.id).join(",");
        let res = await sendMsg(this.send);
        if (res.data.status == 100)
        {
          this.$message('发布成功')
          this.getData();
        }
      }
    },
    sortClict () {
      if (this.multipleSelection !== [] || this.multipleSelection.length > 0)
      {
        const newArr = this.multipleSelection.map(item => item.categoryName)
        const arrSet = new Set(newArr)
        if (arrSet.size > 1)
        {
          this.$message('请选择相同的栏目发布')
          return
        }
      }
      this.sortShow = true
      this.$nextTick(() => {
        this.rowDrop()
      })
      this.sortList = this.multipleSelection
    },
    sortConfirm () {
      this.sortShow = false
      this.publish()
    },
    async publish (item) {
      let data = await this.$publicJS.delConfirm(
        "是否全员发送",
        "是",
        "不是"
      );
      console.log(data, "ttttt");
      if (data)
      {
        // let result = await findOrgData();
        // if (result.data.msg == "SUCCESS")
        // {
        //   if (item)
        //   {
        //     this.orgData = [item];

        //   }
        //   this.orgData = result.data.data;
        //   this.dialogOrgData = true;
        // }
        this.sureOrgData()
      } else
      {
        this.sendMsg();
      }
    },
    gotoPublish (isNew, id = "") {
      this.$router.push({
        path: "/newNews",
        query: {
          isNew: isNew,
          id: id,
        },
      });
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
  },
};
</script>

<style scoped>
.dialog {
  text-align: right;
  margin-top: 1rem;
}

.search {
  display: flex;
  flex-flow: wrap;
  margin-bottom: 2rem;
}

.tables {
  margin: 0 1rem;
}
</style>
